package com.school.controller;

import com.school.common.PageRequest;
import com.school.common.PageResult;
import com.school.common.Result;
import com.school.entity.Dormitory;
import com.school.service.DormitoryService;
import com.school.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 宿舍控制器
 */
@Slf4j
@RestController
@RequestMapping("/dormitory")
public class DormitoryController {
    
    @Autowired
    private DormitoryService dormitoryService;
    
    /**
     * 添加宿舍
     */
    @PostMapping("/add")
    public Result<Long> add(@Validated @RequestBody Dormitory dormitory) {
        Long id = dormitoryService.add(dormitory);
        return Result.success("添加成功", id);
    }
    
    /**
     * 更新宿舍
     */
    @PostMapping("/update")
    public Result<Void> update(@Validated @RequestBody Dormitory dormitory) {
        dormitoryService.update(dormitory);
        return Result.success("更新成功");
    }
    
    /**
     * 删除宿舍
     */
    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        dormitoryService.delete(id);
        return Result.success("删除成功");
    }
    
    /**
     * 批量删除宿舍
     */
    @PostMapping("/batch-delete")
    public Result<Map<String, Object>> batchDelete(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的宿舍");
            }
            log.info("批量删除宿舍，数量: {}", ids.size());
            int count = dormitoryService.batchDelete(ids);
            Map<String, Object> result = new HashMap<>();
            result.put("count", count);
            return Result.success("批量删除成功，共删除 " + count + " 条数据", result);
        } catch (Exception e) {
            log.error("批量删除宿舍失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询宿舍
     */
    @GetMapping("/get/{id}")
    public Result<Dormitory> getById(@PathVariable Long id) {
        Dormitory dormitory = dormitoryService.getById(id);
        return Result.success(dormitory);
    }
    
    /**
     * 查询所有宿舍
     */
    @GetMapping("/all")
    public Result<List<Dormitory>> getAllDormitories() {
        List<Dormitory> dormitories = dormitoryService.getAllDormitories();
        return Result.success(dormitories);
    }
    
    /**
     * 分页查询宿舍列表
     */
    @GetMapping("/list")
    public Result<PageResult<Dormitory>> getList(
            @RequestParam(required = false) String building,
            @RequestParam(required = false) String roomNumber,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPageNum(pageNum);
        pageRequest.setPageSize(pageSize);
        
        PageResult<Dormitory> pageResult = dormitoryService.getPageList(
                building, roomNumber, status, pageRequest);
        return Result.success(pageResult);
    }
    
    /**
     * 导入宿舍数据
     */
    @PostMapping("/import")
    public Result<String> importData(@RequestParam("file") MultipartFile file) {
        try {
            List<Map<String, String>> dataList = ExcelUtils.importExcel(file.getInputStream());
            List<Dormitory> dormitories = new ArrayList<>();
            
            for (Map<String, String> data : dataList) {
                Dormitory dormitory = new Dormitory();
                dormitory.setBuilding(data.get("楼栋"));
                dormitory.setRoomNumber(data.get("宿舍号"));
                
                String floorStr = data.get("楼层");
                if (floorStr != null && !floorStr.isEmpty()) {
                    dormitory.setFloor(Integer.parseInt(floorStr));
                }
                
                String capacityStr = data.get("容纳人数");
                if (capacityStr != null && !capacityStr.isEmpty()) {
                    dormitory.setCapacity(Integer.parseInt(capacityStr));
                }
                
                String occupiedStr = data.get("已入住");
                if (occupiedStr != null && !occupiedStr.isEmpty()) {
                    dormitory.setOccupied(Integer.parseInt(occupiedStr));
                } else {
                    dormitory.setOccupied(0);
                }
                
                String status = data.get("状态");
                dormitory.setStatus(status != null && !status.isEmpty() ? status : "可用");
                dormitory.setRemark(data.get("备注"));
                
                dormitories.add(dormitory);
            }
            
            int count = dormitoryService.batchImport(dormitories);
            return Result.success("导入成功，共导入 " + count + " 条数据");
        } catch (Exception e) {
            log.error("导入宿舍数据失败", e);
            return Result.error("导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出宿舍数据
     */
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) {
        try {
            List<Dormitory> dormitories = dormitoryService.getAllDormitories();
            
            List<String> headers = Arrays.asList(
                    "楼栋", "宿舍号", "楼层", "容纳人数", "已入住", "空余床位", "状态", "备注"
            );
            
            List<List<Object>> dataList = new ArrayList<>();
            for (Dormitory dormitory : dormitories) {
                List<Object> row = Arrays.asList(
                        dormitory.getBuilding(),
                        dormitory.getRoomNumber(),
                        dormitory.getFloor(),
                        dormitory.getCapacity(),
                        dormitory.getOccupied(),
                        dormitory.getAvailable(),
                        dormitory.getStatus(),
                        dormitory.getRemark()
                );
                dataList.add(row);
            }
            
            String fileName = "宿舍列表_" + System.currentTimeMillis();
            ExcelUtils.exportExcel(response, fileName, "宿舍信息", headers, dataList);
        } catch (IOException e) {
            log.error("导出宿舍数据失败", e);
        }
    }
    
    /**
     * 下载导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            List<String> headers = Arrays.asList(
                    "楼栋", "宿舍号", "楼层", "容纳人数", "已入住", "状态", "备注"
            );
            
            List<List<Object>> dataList = new ArrayList<>();
            dataList.add(Arrays.asList("A栋", "101", 1, 4, 4, "满员", ""));
            dataList.add(Arrays.asList("A栋", "102", 1, 4, 3, "可用", ""));
            
            String fileName = "宿舍导入模板";
            ExcelUtils.exportExcel(response, fileName, "宿舍信息", headers, dataList);
        } catch (IOException e) {
            log.error("下载模板失败", e);
        }
    }
}

